import { onMounted, onUnmounted } from "vue"
// import axios from "axios";
import { URL_WEB_LOG } from "./api";
import { post } from "./request";

export function Log() {

    let time = Date.now();
    let stay = readStay();

    function readStay() {
        let str = localStorage.getItem("stay");
        if (str) {
            return JSON.parse(str);
        }
        return {};
    }

    function saveStay() {
        localStorage.setItem("stay", JSON.stringify(stay))
    }

    function onShow() {
        if (document.visibilityState === "visible") {
            // 页面从隐藏状态切换到可见状态时执行的代码
            console.log("页面已显示", location.href);
            time = Date.now();
        } else if (document.visibilityState === "hidden") {
            // 页面从可见状态切换到隐藏状态时执行的代码
            onHide();
        }
    }

    function onHide(synchronous = false) {
        console.log("页面已隐藏", location.href);
        let t = Math.floor((Date.now() - time) / 1000);
        console.log("timer", location.href, t);
        let url = filter(location.href);
        stay[url] = t;
        saveStay();
        time = Date.now();

        // const blob = new Blob([JSON.stringify({ time: t, url })], {
        //     type: "application/json; charset=UTF-8",
        // });
        // navigator.sendBeacon(URL_WEB_LOG, blob);

        if (synchronous) {
            syncSend({ time: t, url })
        }
        else {
            send({ time: t, url });
        }
    }

    function syncSend(data: any) {
        const token = localStorage.getItem("token");
        const headers: any = {
            "Content-Type": "application/json",
        };
        if (token) {
            headers["Authorization"] = `Bearer ${token}`;
        }
        fetch(URL_WEB_LOG, {
            method: "POST",
            headers,
            body: JSON.stringify(data),
            // 保持连接
            keepalive: true,
        });
        localStorage.setItem("SendState", (new Date()).toISOString())

        // const blob = new Blob([JSON.stringify(data)], {
        //     type: "application/json; charset=UTF-8",
        // });
        // navigator.sendBeacon(URL_WEB_LOG, blob);
    }

    function send(data: any) {
        post(URL_WEB_LOG, data, true, 1).then(res => {
            console.log(res);
        }).catch(e => {
            console.log(e);
            console.log("发送错误", e.code)
        })
    }


    function filter(url: string) {
        let list = ["/coin", "/entity", "/token", "/address"];
        let t = list.find(i => url.includes(i));
        if (t) {
            url = location.origin + t;
        }
        // if(url.includes("http") == false){
        //     url = location.origin + url;
        // }
        // if (url.includes("/ranks")) {
        //     url = "/ranks";
        // }
        // if (url.includes("/coin")) {
        //     url = "/coin";
        // }
        // if (url.includes("/entity")) {
        //     url = "/entity";
        // }
        // if (url.includes("/token")) {
        //     url = "/token";
        // }
        // if (url.includes("/address")) {
        //     url = "/address";
        // }
        return url;
    }


    function init(router: any) {
        document.addEventListener("visibilitychange", onShow);
        window.addEventListener("beforeunload", function (event) {
            // localStorage.setItem("beforeunload", (new Date()).toUTCString());
            onHide(true);
        });

        router.beforeEach((to: any, from: any, next: any) => {
            // 在路由切换前执行的代码
            console.error('路由已变化', from.path, to.path, location.href);
            let fp = filter(from.path)
            let tp = filter(to.path)
            if (fp == tp) {
                console.log("no change path")
            }
            else {
                onHide();
            }
            next();
        });
    }

    return { init };
}